package com.demo.heima;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lkz
 * @className Test13
 * @description 两阶段终止
 * @date 2024/6/12 16:26
 **/
public class Test13 {

    public static void main(String[] args) {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tpt.stop();
    }

}

@Slf4j
class TwoPhaseTermination{

    private  Thread monitorThread;

    public void start(){
        monitorThread = new Thread(()->{
            while(true){
                Thread current = Thread.currentThread();
                if(current.isInterrupted()){
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 异常会清楚打断标志 所以重新设置
                    // 防止异常重新设置打断标记
                    current.interrupt();
                }
            }
        },"monitorThread");

        monitorThread.start();
    }

    public void stop() {
        monitorThread.interrupt();
    }


}